package com.lagou.edu.gateway.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * @author liangzj
 * @date 2021/6/26 18:38
 */
@Component
public class TokenCheckFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        if (!request.getURI().getPath().contains("/user/info")) {
            return chain.filter(exchange);
        }

        // 未登录返回
        HttpCookie tokenCookie = exchange.getRequest().getCookies().getFirst("authToken");
        boolean existToken = Objects.nonNull(tokenCookie) && StringUtils.isNotBlank(tokenCookie.getValue());
        if (!existToken) {
            response.setStatusCode(HttpStatus.TEMPORARY_REDIRECT);
            return response.setComplete();
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 2;
    }
}
